package cn.accjiyun.translator.util;

import java.util.Iterator;

import cn.accjiyun.translator.model.TextRoom;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class AnalyzingXml {

	private boolean isBasicNode;
	private String nowkey = new String();
	private StringBuilder nowWebExplain = new StringBuilder();
	TextRoom textRoom;
	
	public AnalyzingXml(TextRoom textRoom) {

		this.textRoom = textRoom;

		try {
			// 创建saxReader对象
			SAXReader reader = new SAXReader();
			// 通过read方法读取一个文件 转换成Document对象
			BufferFolder bufferFolder = new BufferFolder();
			Document document = reader.read(bufferFolder + "data.xml");
			// 获取根节点元素对象
			Element rootNode = document.getRootElement();
			
			Element errorCodeNode = rootNode.element("errorCode");
			
			if (!errorCodeNode.getText().equals("0")) {
				textRoom.setErrorCode(errorCodeNode.getText());
				return;
			}
			
			Element basicNode = rootNode.element("basic");
			Element webNode = rootNode.element("web");

			Element paragraphNode = rootNode.element("translation").element("paragraph");
			textRoom.setTranslation(paragraphNode.getText() + "\n");

			if (basicNode != null) {
				isBasicNode = true;
				listNodes(basicNode);
			}

			if (webNode != null) {
				isBasicNode = false;
				listNodes(webNode);
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	public void listNodes(Element node) {

		if (!(node.getTextTrim().equals(""))) {
			if (isBasicNode) {
				if (node.getName().equals("us-phonetic")) {
					textRoom.setUsphonetic(node.getText());
				} else if (node.getName().equals("uk-phonetic")) {
					textRoom.setUkphonetic(node.getText());
				} else if (node.getParent().getName().equals("explains")) {
					textRoom.appendBasicExplains(node.getText() + "\n");
				}
			} else if (!isBasicNode) {
				if (node.getName().equals("key")) {
					nowkey = node.getText();
					nowWebExplain = new StringBuilder();
				} else if (node.getParent().getName().equals("value")) {
					nowWebExplain.append(node.getText() + " ");
					textRoom.putWebExplains(nowkey, nowWebExplain);
				}
			}
		}

		// 当前节点下面子节点迭代器
		Iterator<Element> it = node.elementIterator();
		// 遍历
		while (it.hasNext()) {
			// 获取某个子节点对象
			Element e = it.next();
			// 对子节点进行遍历
			listNodes(e);
		}
	}
}
